<template>
    <div class="friend-container">
        <div class="friend-card">
            <div class="friend-header">
                <h1>好友列表</h1>
                <div class="header-actions">
                    <button class="action-btn refresh-btn" title="刷新" @click="refreshData">
                        <el-icon>
                            <Refresh />
                        </el-icon>
                    </button>
                    <button
                        class="action-btn add-btn"
                        title="添加好友"
                        @click="addFriendDialogVisible = true"
                    >
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </button>
                    <button class="action-btn back-btn" title="返回" @click="goBack">
                        <el-icon>
                            <ArrowLeft />
                        </el-icon>
                    </button>
                </div>
            </div>

            <div class="friend-content">
                <div class="friend-sidebar">
                    <div class="search-box">
                        <input v-model="searchQuery" placeholder="搜索好友..." type="text" />
                    </div>

                    <div class="friend-list">
                        <div v-if="loading" class="loading-message">加载中...</div>
                        <div v-else-if="friendsList.length === 0" class="empty-message">
                            暂无好友，快去添加吧！
                        </div>
                        <div
                            v-for="friend in filteredFriends"
                            v-else
                            :key="friend.id"
                            class="friend-item"
                        >
                            <div class="friend-avatar">
                                <img
                                    :alt="friend.username"
                                    :src="
                                        friend.photo ||
                                        'https://www.helloimg.com/i/2024/12/22/6767fd5a3cf23.jpg'
                                    "
                                />
                                <div :class="{ online: friend.online }" class="friend-status"></div>
                            </div>
                            <div class="friend-info">
                                <div class="friend-name">{{ friend.username }}</div>
                                <div class="friend-detail">
                                    <span class="friend-level">Lv.{{ friend.level || 1 }}</span>
                                    <span class="friend-rating"
                                        >段位: {{ friend.rating || 0 }}</span
                                    >
                                </div>
                            </div>
                            <div class="friend-actions">
                                <button
                                    class="friend-action-btn chat-btn"
                                    title="发起对话"
                                    @click="startChat(friend)"
                                >
                                    <el-icon>
                                        <ChatDotRound />
                                    </el-icon>
                                </button>
                                <button
                                    class="friend-action-btn delete-btn"
                                    title="删除好友"
                                    @click="confirmDelete(friend)"
                                >
                                    <el-icon>
                                        <Delete />
                                    </el-icon>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="friend-requests">
                    <div class="requests-header">
                        <h2>好友申请</h2>
                        <span v-if="friendRequests.length > 0" class="request-count">{{
                            friendRequests.length
                        }}</span>
                    </div>

                    <div class="requests-list">
                        <div v-if="friendRequests.length === 0" class="empty-message">
                            暂无好友申请
                        </div>
                        <div
                            v-for="request in friendRequests"
                            v-else
                            :key="request.id"
                            class="request-item"
                        >
                            <div class="request-avatar">
                                <img
                                    :alt="request.senderName"
                                    :src="
                                        request.senderPhoto ||
                                        'https://www.helloimg.com/i/2024/12/22/6767fd5a3cf23.jpg'
                                    "
                                />
                            </div>
                            <div class="request-info">
                                <div class="request-name">{{ request.senderName }}</div>
                                <div class="request-time">{{ request.createTime }}</div>
                            </div>
                            <div class="request-actions">
                                <button
                                    class="request-action-btn accept-btn"
                                    title="接受"
                                    @click="handleFriendRequest(request, true)"
                                >
                                    <el-icon>
                                        <Check />
                                    </el-icon>
                                </button>
                                <button
                                    class="request-action-btn reject-btn"
                                    title="拒绝"
                                    @click="handleFriendRequest(request, false)"
                                >
                                    <el-icon>
                                        <Close />
                                    </el-icon>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 删除好友确认对话框 -->
    <el-dialog
        v-model="confirmDeleteDialogVisible"
        :show-close="false"
        center
        class="friend-dialog"
        title="删除好友"
        width="400px"
    >
        <div class="dialog-content">
            确定要删除好友 <span class="highlight">{{ selectedFriend?.username }}</span> 吗？
        </div>
        <template #footer>
            <div class="dialog-footer">
                <button class="dialog-btn cancel" @click="confirmDeleteDialogVisible = false">
                    取消
                </button>
                <button class="dialog-btn confirm delete" @click="deleteFriend">确认删除</button>
            </div>
        </template>
    </el-dialog>

    <!-- 添加好友对话框 -->
    <el-dialog
        v-model="addFriendDialogVisible"
        :show-close="false"
        center
        class="friend-dialog"
        title="添加好友"
        width="400px"
    >
        <div class="dialog-content">
            <div class="form-item">
                <label>好友ID</label>
                <input v-model="friendIdToAdd" placeholder="请输入要添加的好友ID" type="text" />
            </div>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <button class="dialog-btn cancel" @click="addFriendDialogVisible = false">
                    取消
                </button>
                <button class="dialog-btn confirm" @click="sendFriendRequest">发送请求</button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
    import { computed, onMounted, ref } from 'vue'
    import { useRouter } from 'vue-router'
    import { useUserStore } from '@/stores/user'
    import { ElDialog, ElMessage } from 'element-plus'
    import {
        ArrowLeft,
        ChatDotRound,
        Check,
        Close,
        Delete,
        Plus,
        Refresh,
    } from '@element-plus/icons-vue'
    import axios from 'axios'
    import dayjs from 'dayjs'

    const router = useRouter()
    const userStore = useUserStore()

    // 好友列表数据
    const friendsList = ref([])
    // 好友申请列表
    const friendRequests = ref([])
    // 加载状态
    const loading = ref(false)
    // 对话框控制
    const confirmDeleteDialogVisible = ref(false)
    const addFriendDialogVisible = ref(false)
    // 当前选中的好友（用于删除操作）
    const selectedFriend = ref(null)
    // 搜索好友
    const searchQuery = ref('')
    // 添加好友ID
    const friendIdToAdd = ref('')

    // 获取好友列表
    const getFriendsList = async () => {
        loading.value = true
        try {
            const response = await axios.get(
                'http://127.0.0.1:8080/api/friend-relation/getFriendList/',
                {
                    headers: {
                        Authorization: `Bearer ${userStore.token}`,
                    },
                }
            )

            if (response.data.code === 1) {
                friendsList.value = response.data.data.map((friend) => ({
                    ...friend,
                    online: Math.random() > 0.5, // 暂时保留在线状态随机生成
                }))
                ElMessage.success('好友列表获取成功')
            } else {
                throw new Error(response.data.message)
            }
        } catch (error) {
            console.error('获取好友列表错误:', error)
            ElMessage.error('获取好友列表失败，请稍后重试')
        } finally {
            loading.value = false
        }
    }

    // 获取好友申请列表
    const getFriendRequests = async () => {
        try {
            const response = await axios.get(
                'http://127.0.0.1:8080/api/friend-relation/getFriendRequests/',
                {
                    headers: {
                        Authorization: `Bearer ${userStore.token}`,
                    },
                }
            )

            if (response.data.code === 1) {
                friendRequests.value = response.data.data.map((request) => ({
                    ...request,
                    createTime: dayjs(request.createTime).format('YYYY-MM-DD HH:mm:ss'),
                }))
            } else {
                throw new Error(response.data.message)
            }
        } catch (error) {
            console.error('获取好友申请错误:', error)
            ElMessage.error('获取好友申请失败，请稍后重试')
        }
    }

    // 开始聊天
    const startChat = (friend) => {
        // 跳转到聊天界面
        router.push({
            path: '/chat/',
            query: { friendId: friend.id },
        })
    }

    // 确认删除好友对话框
    const confirmDelete = (friend) => {
        selectedFriend.value = friend
        confirmDeleteDialogVisible.value = true
    }

    // 删除好友
    const deleteFriend = async () => {
        if (!selectedFriend.value) return

        try {
            const response = await axios.delete(
                `http://127.0.0.1:8080/api/friend-relation/deleteFriend/?friendId=${selectedFriend.value.id}`,
                {
                    headers: {
                        Authorization: `Bearer ${userStore.token}`,
                    },
                }
            )

            if (response.data.code === 1) {
                // 从列表中移除该好友
                friendsList.value = friendsList.value.filter(
                    (f) => f.id !== selectedFriend.value.id
                )
                ElMessage.success(response.data.message || '好友删除成功')
                confirmDeleteDialogVisible.value = false
            } else {
                throw new Error(response.data.message)
            }
        } catch (error) {
            console.error('删除好友错误:', error)
            ElMessage.error(error.message || '删除好友失败，请稍后重试')
        }
    }

    // 处理好友申请（接受或拒绝）
    const handleFriendRequest = async (request, accept) => {
        try {
            const response = await axios.post(
                accept
                    ? 'http://127.0.0.1:8080/api/friend-relation/acceptRequest/'
                    : 'http://127.0.0.1:8080/api/friend-relation/declineRequest/',
                { friendId: request.senderId },
                {
                    headers: {
                        Authorization: `Bearer ${userStore.token}`,
                    },
                }
            )

            if (response.data.code === 1) {
                // 从申请列表中移除
                friendRequests.value = friendRequests.value.filter((r) => r.id !== request.id)

                if (accept) {
                    // 如果接受，重新获取好友列表
                    await getFriendsList()
                    ElMessage.success('已接受好友申请')
                } else {
                    ElMessage.info('已拒绝好友申请')
                }
            } else {
                throw new Error(response.data.message)
            }
        } catch (error) {
            console.error('处理好友申请错误:', error)
            ElMessage.error(error.message || '处理好友申请失败，请稍后重试')
        }
    }

    // 发送好友申请
    const sendFriendRequest = async () => {
        if (!friendIdToAdd.value.trim()) {
            ElMessage.warning('请输入好友ID')
            return
        }

        try {
            const response = await axios.post(
                'http://127.0.0.1:8080/api/friend-relation/sendRequest/',
                { friendId: friendIdToAdd.value },
                {
                    headers: {
                        Authorization: `Bearer ${userStore.token}`,
                    },
                }
            )

            if (response.data.code === 1) {
                ElMessage.success(response.data.message || '好友申请已发送')
                friendIdToAdd.value = ''
                addFriendDialogVisible.value = false
            } else {
                throw new Error(response.data.message || '发送好友申请失败')
            }
        } catch (error) {
            console.error('发送好友申请错误:', error)
            ElMessage.error(error.message || '发送好友申请失败，请稍后重试')
        }
    }

    // 刷新数据
    const refreshData = () => {
        getFriendsList()
        getFriendRequests()
    }

    // 返回主菜单
    const goBack = () => {
        router.push('/')
    }

    // 过滤好友列表
    const filteredFriends = computed(() => {
        if (!searchQuery.value) return friendsList.value

        const query = searchQuery.value.toLowerCase()
        return friendsList.value.filter((friend) => friend.username.toLowerCase().includes(query))
    })

    onMounted(() => {
        // 从服务器获取好友列表和申请
        getFriendsList()
        getFriendRequests()
    })
</script>

<style scoped>
    .friend-container {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
        width: 100vw;
    }

    .friend-card {
        width: 900px;
        height: 600px;
        background-color: rgba(0, 0, 0, 0.7);
        border-radius: 12px;
        padding: 30px;
        box-shadow: 0 0 30px rgba(255, 215, 0, 0.3);
        border: 1px solid rgba(255, 215, 0, 0.3);
        color: #fff;
        animation: fadeIn 0.5s ease-in-out;
        transform: scale(1);
        transition: transform 0.3s ease;
        display: flex;
        flex-direction: column;
    }

    .friend-card:hover {
        transform: scale(1.01);
        box-shadow: 0 0 40px rgba(255, 215, 0, 0.5);
    }

    .friend-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 25px;
        border-bottom: 1px solid rgba(255, 215, 0, 0.3);
        padding-bottom: 15px;
    }

    .friend-header h1 {
        font-size: 28px;
        color: #ffd700;
        text-shadow: 0 0 10px rgba(255, 215, 0, 0.5);
        margin: 0;
        letter-spacing: 2px;
    }

    .header-actions {
        display: flex;
        gap: 10px;
    }

    .action-btn {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        border: none;
        background-color: rgba(0, 0, 0, 0.3);
        color: #fff;
        cursor: pointer;
        transition: all 0.3s;
    }

    .action-btn:hover {
        transform: translateY(-3px);
    }

    .refresh-btn {
        border: 1px solid rgba(255, 215, 0, 0.5);
        color: #ffd700;
    }

    .refresh-btn:hover {
        background-color: rgba(255, 215, 0, 0.1);
    }

    .add-btn {
        border: 1px solid rgba(103, 194, 58, 0.5);
        color: #67c23a;
    }

    .add-btn:hover {
        background-color: rgba(103, 194, 58, 0.1);
    }

    .back-btn {
        border: 1px solid rgba(144, 147, 153, 0.5);
        color: #909399;
    }

    .back-btn:hover {
        background-color: rgba(144, 147, 153, 0.1);
    }

    .friend-content {
        display: flex;
        flex: 1;
        gap: 20px;
        overflow: hidden;
    }

    .friend-sidebar {
        flex: 2;
        display: flex;
        flex-direction: column;
        border-right: 1px solid rgba(255, 215, 0, 0.2);
        padding-right: 20px;
    }

    .search-box {
        margin-bottom: 15px;
    }

    .search-box input {
        width: 93%;
        background-color: rgba(255, 255, 255, 0.1);
        border: 1px solid rgba(255, 215, 0, 0.3);
        border-radius: 6px;
        padding: 12px 15px;
        color: white;
        font-size: 16px;
        transition: all 0.3s;
    }

    .search-box input:focus {
        outline: none;
        border-color: #ffd700;
        box-shadow: 0 0 8px rgba(255, 215, 0, 0.6);
    }

    .friend-list {
        flex: 1;
        overflow-y: auto;
        padding-right: 5px;
    }

    .friend-list::-webkit-scrollbar {
        width: 6px;
    }

    .friend-list::-webkit-scrollbar-track {
        background: rgba(255, 255, 255, 0.1);
        border-radius: 3px;
    }

    .friend-list::-webkit-scrollbar-thumb {
        background-color: rgba(255, 215, 0, 0.5);
        border-radius: 3px;
    }

    .friend-item {
        display: flex;
        align-items: center;
        padding: 12px;
        border-radius: 8px;
        margin-bottom: 10px;
        background-color: rgba(255, 255, 255, 0.05);
        transition: all 0.3s;
        cursor: pointer;
    }

    .friend-item:hover {
        background-color: rgba(255, 215, 0, 0.1);
        transform: translateX(5px);
    }

    .friend-avatar {
        position: relative;
        width: 50px;
        height: 50px;
        border-radius: 50%;
        overflow: hidden;
        border: 2px solid rgba(255, 215, 0, 0.5);
        margin-right: 15px;
    }

    .friend-avatar img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .friend-status {
        position: absolute;
        bottom: 2px;
        right: 2px;
        width: 12px;
        height: 12px;
        border-radius: 50%;
        background-color: #ff0000;
        border: 2px solid rgba(0, 0, 0, 0.7);
    }

    .friend-status.online {
        background-color: #55ff00;
    }

    .friend-info {
        flex: 1;
    }

    .friend-name {
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 5px;
    }

    .friend-detail {
        font-size: 12px;
        color: rgba(255, 255, 255, 0.7);
        display: flex;
        gap: 10px;
    }

    .friend-level {
        color: #ffd700;
    }

    .friend-rating {
        color: #ff9900;
    }

    .friend-actions {
        display: flex;
        gap: 10px;
    }

    .friend-action-btn {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        border: none;
        background-color: rgba(0, 0, 0, 0.3);
        color: #fff;
        cursor: pointer;
        transition: all 0.3s;
    }

    .friend-action-btn:hover {
        transform: translateY(-3px);
    }

    .chat-btn {
        border: 1px solid rgba(64, 158, 255, 0.5);
        color: #409eff;
    }

    .chat-btn:hover {
        background-color: rgba(64, 158, 255, 0.1);
    }

    .delete-btn {
        border: 1px solid rgba(255, 87, 87, 0.5);
        color: #ff5757;
    }

    .delete-btn:hover {
        background-color: rgba(255, 87, 87, 0.1);
    }

    .friend-requests {
        flex: 1;
        display: flex;
        flex-direction: column;
    }

    .requests-header {
        display: flex;
        align-items: center;
        margin-bottom: 15px;
    }

    .requests-header h2 {
        font-size: 20px;
        color: #ffd700;
        margin: 0;
    }

    .request-count {
        background-color: #ff5757;
        color: white;
        font-size: 12px;
        border-radius: 50%;
        width: 20px;
        height: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-left: 10px;
    }

    .requests-list {
        flex: 1;
        overflow-y: auto;
        padding-right: 5px;
    }

    .requests-list::-webkit-scrollbar {
        width: 6px;
    }

    .requests-list::-webkit-scrollbar-track {
        background: rgba(255, 255, 255, 0.1);
        border-radius: 3px;
    }

    .requests-list::-webkit-scrollbar-thumb {
        background-color: rgba(255, 215, 0, 0.5);
        border-radius: 3px;
    }

    .request-item {
        display: flex;
        align-items: center;
        padding: 12px;
        border-radius: 8px;
        margin-bottom: 10px;
        background-color: rgba(255, 255, 255, 0.05);
        transition: all 0.3s;
    }

    .request-item:hover {
        background-color: rgba(255, 215, 0, 0.1);
    }

    .request-avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        overflow: hidden;
        border: 2px solid rgba(255, 215, 0, 0.5);
        margin-right: 15px;
    }

    .request-avatar img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .request-info {
        flex: 1;
    }

    .request-name {
        font-size: 14px;
        font-weight: bold;
        margin-bottom: 4px;
    }

    .request-time {
        font-size: 12px;
        color: rgba(255, 255, 255, 0.5);
    }

    .request-actions {
        display: flex;
        gap: 8px;
    }

    .request-action-btn {
        width: 30px;
        height: 30px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        border: none;
        background-color: rgba(0, 0, 0, 0.3);
        color: #fff;
        cursor: pointer;
        transition: all 0.3s;
    }

    .request-action-btn:hover {
        transform: translateY(-3px);
    }

    .accept-btn {
        border: 1px solid rgba(103, 194, 58, 0.5);
        color: #67c23a;
    }

    .accept-btn:hover {
        background-color: rgba(103, 194, 58, 0.1);
    }

    .reject-btn {
        border: 1px solid rgba(255, 87, 87, 0.5);
        color: #ff5757;
    }

    .reject-btn:hover {
        background-color: rgba(255, 87, 87, 0.1);
    }

    .loading-message,
    .empty-message {
        text-align: center;
        padding: 30px 10px;
        color: rgba(255, 255, 255, 0.5);
        font-style: italic;
    }

    /* 对话框样式 */
    :deep(.friend-dialog) {
        background-color: rgba(0, 0, 0, 0.8);
        border-radius: 10px;
        border: 1px solid rgba(255, 215, 0, 0.3);
    }

    :deep(.friend-dialog .el-dialog__header) {
        padding: 20px;
        text-align: center;
        border-bottom: 1px solid rgba(255, 215, 0, 0.2);
    }

    :deep(.friend-dialog .el-dialog__title) {
        color: #ffd700;
        font-size: 20px;
    }

    :deep(.friend-dialog .el-dialog__body) {
        padding: 30px;
        color: white;
    }

    .dialog-content {
        text-align: center;
        font-size: 16px;
    }

    .highlight {
        color: #ffd700;
        font-weight: bold;
    }

    .dialog-footer {
        display: flex;
        justify-content: center;
        gap: 20px;
        padding-top: 10px;
    }

    .dialog-btn {
        padding: 10px 20px;
        border-radius: 6px;
        font-size: 16px;
        font-weight: bold;
        cursor: pointer;
        transition: all 0.3s;
        border: none;
    }

    .dialog-btn.cancel {
        background-color: #666;
        color: white;
    }

    .dialog-btn.cancel:hover {
        background-color: #555;
    }

    .dialog-btn.confirm {
        background-color: #ffd700;
        color: #000;
    }

    .dialog-btn.confirm:hover {
        background-color: #ffc000;
        box-shadow: 0 5px 15px rgba(255, 215, 0, 0.4);
    }

    .dialog-btn.confirm.delete {
        background-color: #ff5757;
        color: white;
    }

    .dialog-btn.confirm.delete:hover {
        background-color: #ff3838;
        box-shadow: 0 5px 15px rgba(255, 87, 87, 0.4);
    }

    .form-item {
        margin-bottom: 20px;
    }

    .form-item label {
        display: block;
        margin-bottom: 8px;
        font-size: 16px;
        color: #ffd700;
    }

    .form-item input {
        width: 100%;
        background-color: rgba(255, 255, 255, 0.1);
        border: 1px solid rgba(255, 215, 0, 0.3);
        border-radius: 6px;
        padding: 12px 15px;
        color: black;
        font-size: 16px;
        transition: all 0.3s;
    }

    .form-item input:focus {
        outline: none;
        border-color: #ffd700;
        box-shadow: 0 0 8px rgba(255, 215, 0, 0.6);
    }

    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(-20px) scale(0.95);
        }
        to {
            opacity: 1;
            transform: translateY(0) scale(1);
        }
    }
</style>
